<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_Order
{

    // 支付方式
    const PAY_TYPES = array(
         1 => '全款支付',
         2 => '定金支付',
         3 => '线下支付',
    );

    public static function get_status_list()
    {
        $status_list = Model_Member_Order::$statusNames;
        $result = array();
        foreach ($status_list as $status_id => $status_name)
        {
            $result[] = array('id' => $status_id, 'name' => $status_name);
        }
        return $result;

    }

    public static function get_paytype_list()
    {
        $paytype_list = Model_Member_Order::$paytype_names;
        $result = array();
        foreach ($paytype_list as $paytype_id => $paytype_name)
        {
            $result[] = array('id' => $paytype_id, 'name' => $paytype_name);
        }
        return $result;

    }

    public static function search($condition)
    {
        $result = array(
            'row_count' => 0,
            'data' => array()
        );

        $order_list = Model_Member_Order::back_order_list($condition);
        if (count($order_list['lists']) <= 0)
            return $result;
        $data = array();
        foreach ($order_list['lists'] as $order)
        {
            //$data[] = self::to_order_info($order, true);
            $temp= Model_Member_Order::order_info($order['ordersn']);
            $temp['litpic'] = Model_Api_V2_System::reorganized_resource_url($temp['litpic']);
            $temp['pinyin'] = Model_Model::all_model($order['typeid'],'pinyin');
            $temp['add_time'] = date('Y-m-d H:i:s',$temp['addtime']);
            $data[] =$temp;
        }

        $result['row_count'] = $order_list['total'];
        $result['data'] = $data;
        //$result['sql'] = $order_list['sql'];
        return $result;

    }

    private static function to_order_info($order_data, $is_list)
    {
        $order_info = array();
        $order_info['id'] = $order_data['id'];
        $order_info['pid'] = $order_data['pid'];
        $order_info['webid'] = $order_data['webid'];
        $order_info['ordersn'] = $order_data['ordersn'];
        $order_info['memberid'] = $order_data['memberid'];
        $order_info['supplierid'] = $order_data['supplierlist'];
        $order_info['model_type_id'] = $order_data['typeid'];
        $order_info['productname'] = $order_data['productname'];
        $order_info['productautoid'] = $order_data['productautoid'];
        $order_info['usedate'] = $order_data['usedate'];
        $order_info['suitid'] = $order_data['suitid'];
        $order_info['litpic'] = Model_Api_V2_System::reorganized_resource_url($order_data['litpic']);

        $order_info['marketprice'] = $order_data['marketprice'];
        if ($is_list)
        {
            $order_info['addtime'] = $order_data['addtime'];
            $order_info['totalprice'] = Model_Member_Order::order_total_price($order_data['id']);
            $order_info['totalnum'] = $order_data['dingnum'];
        } else
        {
            $order_info['addtime'] = Model_Api_V2_System::format_unixtime($order_data['addtime']);
            $order_info['adultprice'] = $order_data['price'];
            $order_info['adultnum'] = $order_data['dingnum'];
            $order_info['childprice'] = $order_data['childprice'];
            $order_info['childnum'] = $order_data['childnum'];
            $order_info['oldprice'] = $order_data['oldprice'];
            $order_info['oldnum'] = $order_data['oldnum'];
            $order_info['totalprice'] = Model_Member_Order::order_total_price($order_data['id'], $order_data);
            $order_info['totalnum'] = $order_data['dingnum'] + $order_data['childnum'] + $order_data['oldnum'];
            $order_info['privileg_price'] = Model_Member_Order::order_privileg_price($order_data['id'], $order_data);
            $order_info['actual_price'] = $order_info['totalprice'] - $order_info['privileg_price'];
            $order_info['payprice'] = Model_Member_Order::order_total_payprice($order_data['id'], $order_data);
        }


        $order_info['roombalance'] = $order_data['roombalance'];
        $order_info['roombalancenum'] = $order_data['roombalancenum'];
        $order_info['dingjin'] = $order_data['dingjin'];
        $order_info['effective_date'] = $order_data['usedate'];
        $order_info['expiration_date'] = $order_data['departdate'];
        $order_info['ispay'] = $order_data['ispay'];
        $order_info['paysource'] = $order_data['paysource'];
        $order_info['paytime'] = Model_Api_V2_System::format_unixtime($order_data['paytime']);
        $order_info['paytype'] = $order_data['paytype'];
        $order_info['paytype_name'] = Model_Member_Order::$paytype_names[$order_data['paytype']];
        $order_info['status'] = $order_data['status'];
        $order_info['status_name'] = Model_Member_Order::$order_status[$order_data['status']];
        $order_info['linkman'] = $order_data['linkman'];
        $order_info['linktel'] = $order_data['linktel'];
        $order_info['linkemail'] = $order_data['linkemail'];
        $order_info['linkqq'] = $order_data['linkqq'];
        $order_info['finishtime'] = Model_Api_V2_System::format_unixtime($order_data['finishtime']);
        $order_info['ispinlun'] = $order_data['ispinlun'];
        $order_info['isneedpiao'] = $order_data['isneedpiao'];
        $order_info['remark'] = $order_data['remark'];
        $order_info['viewstatus'] = $order_data['viewstatus'];
        $order_info['eticketno'] = $order_data['eticketno'];
        $order_info['isconsume'] = $order_data['isconsume'];
        $order_info['consumetime'] = Model_Api_V2_System::format_unixtime($order_data['consumetime']);
        $order_info['consumeverifyuser'] = $order_data['consumeverifyuser'];
        $order_info['consumeverifymemo'] = $order_data['consumeverifymemo'];
        $order_info['departdate'] = $order_data['departdate'];


        return $order_info;
    }

    public static function get_detail($id,$mid=0)
    {
        if($mid){
            $sql = "SELECT * FROM `sline_member_order` WHERE id={$id} and memberid={$mid}";
        }else{
            $sql = "SELECT * FROM `sline_member_order` WHERE id={$id} ";
        }
        $info = DB::query(Database::SELECT, $sql)->execute()->current();
        if (empty($info))
        {
            return null;
        }

        $result=Model_Member_Order::order_info($info['ordersn']);
        $result['status_name'] = Model_Member_Order::$order_status[$result['status']];
        $result['litpic'] = Model_Api_V2_System::reorganized_resource_url($result['litpic']);
		// 订单编号
		$result['series'] = St_Product::product_series($result['productautoid'], $result['typeid']);
        //会员信息
        $result['member_info'] = array();
        $member = DB::select('*')->from('member')->where('mid', '=', $info['memberid'])->execute()->current();
        if (!empty($member))
        {
            $result['member_info'] = array(
                'id' => $member['mid'],
                'nickname' => $member['nickname'],
                'truename' => $member['truename'],
                'email' => $member['email'],
                'mobile' => $member['mobile'],
                'litpic' => Model_Api_V2_System::reorganized_resource_url($member['litpic'])
            );
        }
        $result['days'] = self::diffBetweenTwoDays($result['usedate'],$result['departdate']);
        // 如果是租车
        if($result['typeid'] == 3)
        {
            $days = strtotime($result['departdate']) - strtotime($result['usedate']);
            $isDate = date('H:i:s', strtotime($result['departdate'])) === '00:00:00';
            $days = ceil($days/60/60/24);//超过1分钟就算一天

            $result['days'] = 1; // 默认值为1
            if ($isDate && $days == 1) {
                $result['days'] = $days + 1;
            } elseif (!$isDate && $days) {
                $result['days'] = $days;
            }
        }
        //游客信息
        $result['tourer_list'] = array();
        if($info['typeid']!=114){
            $tourers = Model_Member_Order_Tourer::get_tourer_by_orderid($info['id']);
         }else{
            $tourers = DB::select()->from('outdoor_tourer')->where('orderid','=',$info['id'])->execute()->as_array();
         }
        if (count($tourers) > 0)
        {
            $result['tourer_list'] = $tourers;
        }

        //发票信息
        $result['fapiao_info'] = '';
        $bill = DB::select()->from('member_order_bill')->where('orderid', '=', $info['id'])->execute()->current();
        if (!empty($bill))
        {
            $result['fapiao_info'] = $bill;
        }
		
        $result["web_url"] =  $GLOBALS['cfg_basehost'];
        $result["add_time"] =  date("Y-m-d H:i:s",$result['addtime']);

        //订单的附加保险
        if (St_Functions::is_system_app_install(111))
        {
            $additional = DB::select()->from('member_order')->where('pid','=',$id)->execute()->as_array();
            $result["additional"] = $additional;
        }
        //获得消费码相关信息

        //验单部分暂时有bug
        if(!empty($result['eticketno']))
        {
            $whereStr = " (a.status='5' OR a.status='2') AND (a.isconsume='1' or b.id is not null)";
            $whereStr .= " AND a.eticketno='{$result['eticketno']}'" ;
            $csql = "select b.dingnum as verified_dingnum,b.childnum as verified_childnum,b.oldnum as verified_oldnum,b.addtime as verified_addtime from sline_member_order a left join sline_member_order_verify b on a.id=b.orderid ";
            $csql .=" where {$whereStr} ";
            //返回当前页的数据结果
            $list =  DB::query(Database::SELECT,$csql)->execute()->as_array();
            $result['current_verified_num']=0;
            foreach ($list as $key=>$vel)
            {
                $result['current_verified_num']+=(intval($vel['verified_dingnum'])+intval($vel['verified_childnum'])+intval($vel['verified_oldnum']));
            }
            $result['eticketno_detail']=$list;
        }else{
            $result['current_verified_num'] = 0;
        }

        if(!Model_Supplier::display_is_open()){
            $result['eticketno']='';
        }

        //获得合同信息
        if(!empty($info['contract_id'])){
            $contract = Model_Api_V2_Contract::get_order_contract($info['id']);
            $result['contract_content']= $contract['status'] ? $contract['data'] : false;
        }

        //stccs升级部分，票二维码显示
        if(St_Functions::is_normal_app_install('supplier_spot_stccs') && $info['typeid'] == 5){
            $stccs_tickets = DB::select()->from('member_order_stccs_ticket_guid')
                ->where('orderid','=',$info['id'])->execute()->as_array();
            $result["stccs_tickets"] = $stccs_tickets;
        }
        // 票付通
        if(St_Functions::is_normal_app_install('system_docs')){
            $docs = DB::select()->from('member_order_docs')->where("ordersn",'=',$result['ordersn'])->execute()->as_array();
            if($docs && $result['status'] == 2){
                foreach ($docs as &$v){
                    $v['ticket_num']  = $v['UUcode'];
                    $v['ticket_guid'] = $v['UUcode'];
                    $v['status']      = 2;
                }
                $result["stccs_tickets"] = $docs;
            }
        }
        // 导游
        if($result['typeid']==106){
            $guide_id = DB::select()->from('guide_service')->where('id','=',$result['productautoid'])->execute()->get('guide_id');
            $guide_mid = DB::select()->from('guide')->where('id','=',$guide_id)->execute()->get('mid');
            $guide_member = DB::select()->from('member')->where('mid','=',$guide_mid)->execute()->current();
            $result['guide_name'] = $guide_member['truename']?:$guide_member['nickname'];
        }
        // 私人定制
        if($result['typeid']==14){
            $customize = DB::select()->from('customize')->where('id','=',$result['productautoid'])->execute()->current();
            $result['adultnum'] = $customize['adultnum'];
            $result['childnum'] = $customize['childnum'];
        }
        //收货地址
        if ($info['receiver_address_id']) {
            $receiver_address   = DB::select()->from('member_address')->where('id', '=', $info['receiver_address_id'])->execute()->current();
            $result['receiver_address'] = $receiver_address;
        }

        //退款信息
        $result = Pay_Online_Refund::get_refund_info($result);

        // 判断订单是否结束
        if($result['status'] == 1 && $result['auto_close_time'] > 0)
        {
            if($result['auto_close_time'] < time())
            {
                $result['status'] = 3; // 订单关闭
            }
            else
            {
                // 计算结束秒数
                $result['close_second'] = $result['auto_close_time'] - time();
            }
        }

        // 快递信息
        $result['express'] = self::get_express_info($info['ordersn']);

        // 优惠券信息处理
        if(!isset($result['iscoupon'])) {
            $result['iscoupon'] = array(
                'name' => null,
                'money' => 0,
                'cmoney' => 0
            );
        }

        return $result;
    }

    // 日期相差天数
    public  static  function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

	// 取消订单
	public static function cancel_order($ordersn)
	{
		$sql = "SELECT * FROM `sline_member_order` WHERE ordersn={$ordersn}";
        $info = DB::query(Database::SELECT, $sql)->execute()->current();
        $org_status = $info['status'];
        if (empty($info))
        {
            return null;
        }
		else
		{

			$sql = "UPDATE sline_member_order SET status=3 WHERE ordersn={$ordersn}";
			$result = DB::query(Database::UPDATE, $sql)->execute();
			if($result)
			{
                $order_info = DB::select()->from('member_order')->where('ordersn', '=', $ordersn)->execute()->current();
                $product_model = St_Product::get_product_model($order_info['typeid']);
                Model_Member_Order::back_order_status_changed($org_status,$order_info,$product_model);
				$status['msg'] = 1;
			}else
			{
				$status['msg'] = 0;
			}
			
			return $status;
		}

	}
    public static function statistics_annual_report($year, $model_type_id = 0)
    {
        $current_year = date('Y');
        if ($current_year < $year)
        {
            return null;
        }

        for ($i = 1; $i <= 12; $i++)
        {
            $starttime = date('Y-m-d', mktime(0, 0, 0, $i, 1, $year)); //开始时间

            $endtime = strtotime("$starttime +1 month -1 day"); //结束时间
            $timearr = array(strtotime($starttime), $endtime);

            $out[$i] = Model_Member_Order::back_order_price_year($timearr, $model_type_id);
        }

        return $out;
    }

    public static function statistics_monthly_report($model_type_id = 0)
    {
        $out = array();

        //今日销售
        $time_arr = St_Functions::back_get_time_range(1);
        $out['today'] = Model_Member_Order::back_caculate_info_by_timerange($time_arr, $model_type_id);

        //昨日销售
        $time_arr = St_Functions::back_get_time_range(2);
        $out['yesterday'] = Model_Member_Order::back_caculate_info_by_timerange($time_arr, $model_type_id);

        //本周销售
        $time_arr = St_Functions::back_get_time_range(3);
        $out['thisweek'] = Model_Member_Order::back_caculate_info_by_timerange($time_arr, $model_type_id);

        //本月销售
        $time_arr = St_Functions::back_get_time_range(5);
        $out['thismonth'] = Model_Member_Order::back_caculate_info_by_timerange($time_arr, $model_type_id);

        return $out;
    }

    /**
     * 创建订单
     * @param $arr
     * @param $product_model
     * @param array $params 一些附加参数
     * @return array|false
     */
    public static function add_order($arr, $product_model, $params = array())
    {
        // 是否允许使用会员抵扣，默认允许使用
        $can_use_member_discount = isset($params['use_member_discount']) ? $params['use_member_discount'] : true;

        $arr['mobile_source']=1;
        $flag = false;
        $msg = '';
        $model = ORM::factory('member_order');
        if (is_array($arr))
        {
            $db = Database::instance();
            $db->begin();
            try
            {
                $uni_img = Model_Uniapp_Images::get_img_list($arr['typeid']);
                if (isset($uni_img[$arr['productautoid']])) {
                    $arr['litpic'] = $uni_img[$arr['productautoid']];
                }

                $arr['ordersn'] = $arr['ordersn'] ?? St_Product::get_ordersn($arr['typeid']);

                if ($params['member_card_id']) {
                    if($arr['typeid']==5){
                        if($arr['haschild']!=1){
                            if (St_Functions::is_normal_app_install('system_card')) {
                                if ($params['card_tourist_id']) {
                                    Model_Card::add_order_tourist(false, $params['card_tourist_id']);
                                }
                                Model_Card::add_reservation_record($arr, $params['member_card_id']);
                                $arr['paytype']   = 4;
                                $arr['paysource'] = '会员卡抵扣';
                            }
                        }
                    }else{
                        if (St_Functions::is_normal_app_install('system_card')) {
                            if ($params['card_tourist_id']) {
                                Model_Card::add_order_tourist(false, $params['card_tourist_id']);
                            }
                            Model_Card::add_reservation_record($arr, $params['member_card_id']);
                            $arr['paytype']   = 4;
                            $arr['paysource'] = '会员卡抵扣';
                        }
                    }
                }

                // 预订总数
                $dingnum = self::total_people_number($arr);

                // 减库存
                if($arr['typeid']!=99 && $arr['typeid']!=5) {
	                $bool = call_user_func(array($product_model, 'storage'), $arr['suitid'], '-' . $dingnum, $arr);
	                if (!$bool)
	                {
	                    throw new Exception('库存不足');
	                }
                }


                if($arr['typeid'] == 104){
                    unset($arr['child_list']);
                }

                //添加供应商信息
                if ($arr['typeid'] != 5) {
                    $arr['supplierlist'] = St_Product::get_product_supplier($arr['typeid'], $arr['productautoid']);
                } else {
                    $suit                = Model_Spot_Suit::suit_info($arr['suitid']);
                    $arr['supplierlist'] = $suit['supplierlist'];
                }

                if($arr['typeid'] == 5 && St_Functions::is_normal_app_install('system_docs')){
                    //检测订单是否是票付通的产品
                    $ticket = DB::select()->from('spot_ticket')->where('id','=',$arr['suitid'])->execute()->current();
                    if($ticket['interface_code'] && strpos($ticket['interface_code'],'aid')){
                        $ids = json_decode($ticket['interface_code'],true);
                        $docs = array(
                            'ordersn' => $arr['ordersn'],
                            'UUid'    => $ids['id'],
                            'UUaid'   => $ids['aid'],
                            'UUpid'   => $ids['pid'],
                            'UUlid'   => $ids['lid'],
                        );
                        DB::insert('member_order_docs', array_keys($docs))->values(array_values($docs))->execute();
                    }
                }

                if (in_array($arr['typeid'], array(1, 2, 5, 8, 114, 118, 121, 104))) {
                    if ($arr['need_confirm'] == 2) {
                        $arr['status'] = 0;
                    } else {
                        $arr['status'] = 1;
                    }
                } else {
                    if ($arr['paytype'] == '3') {
                        $arr['status'] = 0;
                    } else {
                        $arr['status'] = 1;
                    }
                }

                if (empty($arr['typeid']))
                {
                    $arr['typeid'] = 999;
                }

                foreach ($arr as $k => $v)
                {
                    $model->$k = $v;
                }
                $model->save();

                if (!$model->saved())
                {
                    //回滚库存
                    call_user_func(array($product_model, 'storage'), $arr['suitid'], $arr['dingnum'], $arr);
                    throw new Exception('保存失败');
                }
                $db->commit();
            }
            catch (Exception $e)
            {
                $db->rollback();
                return array('status'=>0,'msg'=>$e->getMessage()?$e->getMessage():'保存失败');
            }

            //预订送积分
            $model->jifenbook_id = $arr['jifenbook'];
            $model->jifenbook = St_Product::calculate_jifenbook($arr['jifenbook'], $model->typeid, $model->ordersn);
            $model->update();
            if(St_Functions::is_normal_app_install('memberdiscount') && !$params['member_card_id'] && $can_use_member_discount)
            {
                if(method_exists('Model_Api_V2_Discount','add_order_discount')){
                    Model_Api_V2_Discount::add_order_discount($arr);
                }
            }

            if (isset($arr['memberid']) && $arr['memberid']) {
                if (St_Functions::is_normal_app_install('mobiledistribution') && method_exists('Model_Fenxiao', 'book_data')) {
                    Model_Fenxiao::book_data($arr['ordersn']);
                }
            }

            //添加订单产品的利润报价
   
            if (!in_array($arr['typeid'], array(15,21, 23, 14, 198, 196))) {
                if(!$arr['pid'] || $arr['typeid']==5){
                    St_Product::member_order_extend($arr['ordersn']);
                }
            }


            //订单结算信息表数据存储
            Model_Member_Order_Compute::add($arr['ordersn']);

            // 添加会员卡订单旅客
            if ($params['card_tourist_id']) {
                if (St_Functions::is_normal_app_install('system_card')) {
                    Model_Card::add_order_tourist($model->id, $params['card_tourist_id']);
                }
            }
            //返回状态
            $flag = true;
        }

        return array(
            'msg' => $msg,
            'status' => $flag,
            'order_id' => $model->id,
            'ordersn' => $model->ordersn,
        );
    }

    /**
     * @function 获取快递信息
     */
    public static function get_express_info($ordersn)
    {
        //快递100信息
        $express_info = DB::select("express_company_name", "express_code", "end_time")->from("malls_order_express")->where("ordersn", "=",$ordersn)->execute()->current();
        if ($express_info)
        {
            $auto_time = $express_info['end_time'] - time();
            if ($auto_time > 0)
            {
                $day    = floor($auto_time / 86400);
                $hour   = floor(($auto_time - $day * 86400) / 3600);
                $minute = floor(($auto_time - $day * 86400 - 3600 * $hour) / 60);

                $day_s    = $day > 0 ? $day . '天' : '';
                $hour_s   = $hour > 0 ? $hour . '小时' : '';
                $minute_s = $minute > 0 ? $minute . '分' : '';

                $auto_str                 = $day_s . $hour_s . $minute_s;
                $express_info['auto_str'] = $auto_str;
            }
            else
            { // 自动收货

            }
        }

        return $express_info;
    }

    /**
     * @function 全局订单
     * @param $params
     * @return mixed
     */
    public static function query($params){
        $default=array(
            'row'=>'10',
            'flag'=>'',
            'offset'=>0,
            'typeid'=>0,
            'limit'=>0
        );
        $params=array_merge($default,$params);
        extract($params);
        //获取全部订单
        if($flag=='all')
        {
            $where = ' WHERE typeid IN ( SELECT id FROM sline_model where  id!=14) ';
        }
        else if($flag == 'line') //线路订单
        {
            $where = 'where typeid = 1';
        }
        else if($flag == 'hotel')
        {
            $where = 'where typeid = 2';
        }
        else if($flag == 'car')
        {
            $where = 'where typeid = 3';
        }
        else if($flag == 'spot')
        {
            $where = 'where typeid = 5';
        }
        else if($flag == 'visa')
        {
            $where = 'where typeid = 8';
        }
        else if($flag == 'tuan')
        {
            $where = 'where typeid = 13';
        }
        else
        {
            return array();
        }

        $sql="SELECT * FROM `sline_member_order` {$where} ORDER BY addtime DESC LIMIT $limit,$row";
        $arr = DB::query(1,$sql)->execute()->as_array();
        $newList = array();
        foreach($arr as $row)
        {
            $memberinfo = Model_Member::get_member_info($row['memberid']);
            $newList[] = array(
                'nickname' => $memberinfo['nickname'],
                'title'    => $row['productname'],
                'dingtime' => Product::format_addtime($row['addtime']),
            );
        }
        return $newList;
    }

    /**
     * 获取订单里面的总人数
     * @param $order
     * @return string
     */
    public static function total_people_number($order)
    {
        $dingnum = $order['dingnum'] ?? 0;
        $childnum = $order['childnum'] ?? 0;
        $oldnum = $order['oldnum'] ?? 0;
        $people4_num = $order['people4_num'] ?? 0;
        $people5_num = $order['people5_num'] ?? 0;
        $people6_num = $order['people6_num'] ?? 0;

        $people_number = [$dingnum, $childnum, $oldnum, $people4_num, $people5_num, $people6_num];

        return St_Math::add($people_number, 0);
    }

    /**
     * 获取会员预订数量
     * @param $type_id
     * @param $member_id
     * @param $params array ['suit_id', 'product_id']
     * @return int
     */
    public static function get_member_order_number($type_id, $member_id, $params = array())
    {
        $suit_id    = Arr::get($params, 'suit_id', '');
        $product_id = Arr::get($params, 'product_id', '');

        $builder = DB::select()
            ->from('member_order')
            ->where('memberid', '=', $member_id)
            ->and_where('typeid', '=', $type_id)
            ->and_where('status', 'in', array(0, 1, 2, 5, 6, 7, 8));

        if ($product_id) {
            $builder->and_where('productautoid', '=', $product_id);
        }

        if ($suit_id) {
            $builder->and_where('suitid', '=', $suit_id);
        }

        return $builder->execute()->count();
    }
}